package org.bugjail.integration.mantis.dataaccess.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.Properties;

public class QueryManager {
	private Properties properties;
	Connection connection;
	
	public QueryManager(String fileURL) {
		try {
			properties = new Properties();
			properties.load(getClass().getResourceAsStream(fileURL));
		} catch (Exception e) {
			throw new QueryException(e.getMessage());
		}
	}

	public PreparedStatement getPreparedStatement(String property) {
		try {
			String query = properties.getProperty(property);
			PreparedStatement preparedStatement = null;
			if (connection==null) {
				connection = ConnectionManager.getInstance().connect();
			}
			preparedStatement = connection.prepareStatement(query);
			return preparedStatement;
		} catch (Exception e) {
			throw new QueryException(e.getMessage());
		}
	}

	public java.sql.Date convertDateToSQL(Date date) {
		long time = date.getTime();
		java.sql.Date sqlDate = new java.sql.Date(time);
		return sqlDate;
	}

	public static void close(QueryManager queryManager) {
		if (queryManager!=null) {
			try {
				queryManager.connection.close();
				queryManager.connection=null;
			} catch (Exception e) {
				throw new QueryException(e.getMessage());
			}
		}		
	}

	public static void commit(QueryManager queryManager) {
		try {
			if (queryManager!=null)
				if (queryManager.connection!=null)
					queryManager.connection.commit();
		} catch (SQLException e) {
			throw new QueryException(e.getMessage());
		}
	}

	public static void rollback(QueryManager queryManager) {
		try {
			if (queryManager!=null)
				if (queryManager.connection!=null){
					queryManager.connection.rollback();
					close(queryManager);
				}			
		} catch (SQLException e) {
			throw new QueryException(e.getMessage());
		}
	}
}
